package org.bbmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.bbmall.bean.store.*;
import org.bbmall.dao.*;
import org.bbmall.dto.store.*;
import org.bbmall.service.IStoreAnalysisService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商店分析业务服务实现类
 */
@Service
@RequiredArgsConstructor
public class StoreAnalysisServiceImpl implements IStoreAnalysisService {

    private final AdsStoreOverviewMapper storeOverviewMapper;
    private final AdsStoreSalesRankingTop5Mapper salesRankingMapper;
    private final AdsStoreCustomerDistributionMapper customerDistributionMapper;
    private final AdsLowEfficiencyAlertMapper lowEfficiencyAlertMapper;
    private final AdsStorePerformanceAnalysisMapper performanceAnalysisMapper;
    private final AdsInventoryTurnoverVsSalesMapper inventoryTurnoverMapper;

    /**
     * 获取商店分析仪表板所有数据
     */
    @Override
    public StoreDashboardDataDTO getStoreDashboardData(LocalDate today) {
        StoreDashboardDataDTO dashboardData = new StoreDashboardDataDTO();

        // 1. 设置门店核心指标
        dashboardData.setStoreKpi(buildStoreKpiDTO(today));

        // 2. 设置门店销售排名Top5
        dashboardData.setSalesRanking(buildSalesRankingDTO(today));

        // 3. 设置各店客流分布
        dashboardData.setCustomerDistribution(buildCustomerDistributionDTO(today));

        // 4. 设置低效门店预警
        dashboardData.setLowEfficiencyStores(buildLowEfficiencyStoresDTO(today));

        // 5. 设置门店坪效
        dashboardData.setStorePerformance(buildStorePerformanceDTO(today));

        // 6. 设置门店库存周转率
        dashboardData.setInventoryTurnover(buildInventoryTurnoverDTO(today));

        return dashboardData;
    }

    /**
     * 构建门店核心指标DTO
     */
    private StoreKpiDTO buildStoreKpiDTO(LocalDate statDate) {
        StoreKpiDTO kpiDTO = new StoreKpiDTO();

        // 获取门店总览数据
        AdsStoreOverview overview = getStoreOverviewByDate(statDate);
        if (overview != null) {
            kpiDTO.setTotalStores(overview.getTotalStores());
            kpiDTO.setCoveredCities(overview.getCoveredCities());
            kpiDTO.setOperatingStores(overview.getOperatingStores());
            kpiDTO.setNonOperatingStores(overview.getMaintenanceStores());
            kpiDTO.setTodayCustomers(overview.getTodayCustomers());
            kpiDTO.setAvgStoreSales(overview.getAvgStoreSales());

            // 计算客流变化率
            kpiDTO.setCustomerChangeRate(overview.getGrowthRate()
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(1, RoundingMode.HALF_UP));

            // 计算销售额变化率
            kpiDTO.setSalesChangeRate(overview.getSalesGrowthRate()
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(1, RoundingMode.HALF_UP));
        } else {
            // 设置默认值
            kpiDTO.setTotalStores(0);
            kpiDTO.setCoveredCities(0);
            kpiDTO.setOperatingStores(0);
            kpiDTO.setNonOperatingStores(0);
            kpiDTO.setTodayCustomers(0);
            kpiDTO.setAvgStoreSales(BigDecimal.ZERO);
            kpiDTO.setCustomerChangeRate(BigDecimal.ZERO);
            kpiDTO.setSalesChangeRate(BigDecimal.ZERO);
        }

        return kpiDTO;
    }

    /**
     * 构建门店销售排名DTO
     */
    private List<StoreSalesRankingDTO> buildSalesRankingDTO(LocalDate statDate) {
        QueryWrapper<AdsStoreSalesRankingTop5> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stat_date", statDate)
                .orderByAsc("rank_number");

        List<AdsStoreSalesRankingTop5> rankingList = salesRankingMapper.selectList(queryWrapper);

        return rankingList.stream()
                .map(ranking -> {
                    StoreSalesRankingDTO dto = new StoreSalesRankingDTO();
                    dto.setStoreName(ranking.getStoreName());
                    dto.setSalesAmount(ranking.getDailySales());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建各店客流分布DTO
     */
    private List<StoreCustomerDistributionDTO> buildCustomerDistributionDTO(LocalDate statDate) {
        QueryWrapper<AdsStoreCustomerDistribution> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stat_date", statDate)
                .orderByDesc("daily_customers")
                .last("LIMIT 5"); // 取前5名

        List<AdsStoreCustomerDistribution> distributionList = customerDistributionMapper.selectList(queryWrapper);

        return distributionList.stream()
                .map(distribution -> {
                    StoreCustomerDistributionDTO dto = new StoreCustomerDistributionDTO();
                    dto.setStoreName(distribution.getStoreName());
                    dto.setCustomerCount(distribution.getDailyCustomers());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建低效门店预警DTO
     */
    private List<LowEfficiencyStoreDTO> buildLowEfficiencyStoresDTO(LocalDate statDate) {
        QueryWrapper<AdsLowEfficiencyAlert> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stat_date", statDate)
                .orderByAsc("avg_daily_sales_7d"); // 销售额低的排在前面

        List<AdsLowEfficiencyAlert> alertList = lowEfficiencyAlertMapper.selectList(queryWrapper);

        return alertList.stream()
                .map(alert -> {
                    LowEfficiencyStoreDTO dto = new LowEfficiencyStoreDTO();
                    dto.setStoreName(alert.getStoreName());
                    dto.setDailySales(alert.getAvgDailySales7d());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建门店坪效DTO
     */
    private List<StorePerformanceDTO> buildStorePerformanceDTO(LocalDate statDate) {
        QueryWrapper<AdsStorePerformanceAnalysis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stat_date", statDate)
                .orderByDesc("sales_per_sqm")
                .last("LIMIT 5"); // 取前5名

        List<AdsStorePerformanceAnalysis> performanceList = performanceAnalysisMapper.selectList(queryWrapper);

        return performanceList.stream()
                .map(performance -> {
                    StorePerformanceDTO dto = new StorePerformanceDTO();
                    dto.setStoreName(performance.getStoreName());
                    dto.setPerformance(performance.getSalesPerSqm());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建库存周转率DTO
     */
    private List<InventoryTurnoverDTO> buildInventoryTurnoverDTO(LocalDate statDate) {
        QueryWrapper<AdsInventoryTurnoverVsSales> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stat_date", statDate)
                .orderByDesc("turnover_rate")
                .last("LIMIT 5"); // 取前5名

        List<AdsInventoryTurnoverVsSales> turnoverList = inventoryTurnoverMapper.selectList(queryWrapper);

        return turnoverList.stream()
                .map(turnover -> {
                    InventoryTurnoverDTO dto = new InventoryTurnoverDTO();
                    dto.setTurnoverRate(turnover.getTurnoverRate());
                    dto.setSalesAmount(turnover.getDailySales());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据日期获取门店总览数据
     */
    private AdsStoreOverview getStoreOverviewByDate(LocalDate date) {
        QueryWrapper<AdsStoreOverview> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stat_date", date);
        return storeOverviewMapper.selectOne(queryWrapper);
    }
}